<template>
  <div id="app">
    <Navbar />
    <div class="search-center">
      <button class="all-button" @click="selectAllProducts">all</button>
      <input
        type="text"
        placeholder="search"
        class="search-input"
        v-model="searchKeyword"
      />
      <button class="search-icon">
        <i class="fas fa-search">🔍</i>
      </button>
    </div>

    <div class="favorite-container">
      <div class="left-panel">
        <div class="filter-search">
          <button class="category-button" @click="selectedCategory = '全部'">
            全部
          </button>
          <button class="category-button" @click="selectedCategory = '食品'">
            食品
          </button>
          <button class="category-button" @click="selectedCategory = '物品'">
            物品
          </button>
          <button class="category-button" @click="selectedCategory = '娱乐'">
            娱乐
          </button>
        </div>
      </div>

      <div class="right-panel">
        <div class="product-list">
          <div
            class="product-item"
            v-for="product in filteredProducts"
            :key="product.id"
          >
            <input type="checkbox" v-model="product.isChecked" />
            <img
              :src="product.product.image_url"
              alt="product"
              class="product-image"
            />
            <div class="product-info">
              <span class="product-name">{{ product.product.name }}</span>
              <span class="product-price">¥{{ product.product.price }}</span>
              <button
                class="delete-button"
                @click="deleteSingleProduct(product.id)"
              >
                delete
              </button>
            </div>
          </div>
        </div>

        <button
          class="delete-selected-button"
          @click="deleteSelectedProducts"
          :disabled="!hasSelectedProducts"
        >
          删除
        </button>
      </div>
    </div>

    <footer class="footer-links">
      <div class="link-group">
        <a>关于校麦</a>
        <a>协议及隐私权政策</a>
        <a>廉正举报</a>
        <a>联系合作</a>
      </div>
      <div class="link-group">
        <a>招聘信息</a>
        <a>防骗秘籍</a>
        <a>商户入驻</a>
      </div>
      <div class="copyright">© 2025-2025 校麦网</div>
    </footer>

    <LoginDialog
      v-if="showLoginDialog"
      @close="showLoginDialog = false"
      @login="handleLogin"
    />
    <RegisterDialog
      v-if="showRegisterDialog"
      @close="showRegisterDialog = false"
      @register="handleRegister"
    />
  </div>
</template>

<script setup>
import { ref, watch, computed, onMounted } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import LoginDialog from "../../components/LoginDialog.vue";
import RegisterDialog from "../../components/RegisterDialog.vue";
import Navbar from "../../components/Navbar.vue";

const API_URL = "http://localhost:3000";
const currentUser = ref(localStorage.getItem("currentUser") || null);
const isLoggedIn = ref(!!currentUser.value);
const showLoginDialog = ref(false);
const showRegisterDialog = ref(false);

// 退出登录
const logout = () => {
  localStorage.removeItem("currentUser");
  currentUser.value = null;
  isLoggedIn.value = false;
};

// 登录/注册逻辑（需对接实际接口）
const handleLogin = (userId) => {
  currentUser.value = userId;
  localStorage.setItem("currentUser", userId);
  isLoggedIn.value = true;
};

const handleRegister = async (userData) => {
  try {
    const response = await axios.post(`${API_URL}/users`, {
      ...userData,
      role: "buyer",
      status: "active",
      registeredAt: new Date().toISOString(),
    });
    currentUser.value = response.data.id;
    localStorage.setItem("currentUser", response.data.id);
    isLoggedIn.value = true;
    // 初始化收藏列表
    await axios.post(`${API_URL}/favorites`, {
      userId: response.data.id,
      productId: "", // 初始为空，后续通过接口添加
      product: {},
    });
  } catch (error) {
    ElMessage.error("注册失败，请重试");
  }
};

// 收藏数据管理
const favoriteProducts = ref([]);

// 加载用户收藏
const loadFavorites = async () => {
  if (!currentUser.value) return;
  try {
    const response = await axios.get(`${API_URL}/favorites`, {
      params: { userId: currentUser.value },
    });
    favoriteProducts.value = response.data; // 直接使用返回的收藏数组
  } catch (error) {
    ElMessage.error("加载收藏夹失败");
  }
};

// 筛选逻辑
const searchKeyword = ref("");
const selectedCategory = ref("全部");

const filteredProducts = computed(() => {
  let filtered = [...favoriteProducts.value];

  // 分类筛选（基于 product.type）
  if (selectedCategory.value !== "全部") {
    filtered = filtered.filter(
      (item) => item.product.type === selectedCategory.value
    );
  }

  // 关键词搜索（基于 product.name）
  if (searchKeyword.value) {
    filtered = filtered.filter((item) =>
      item.product.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
    );
  }

  return filtered;
});

// 选中状态
const selectedProducts = computed(() =>
  filteredProducts.value.filter((item) => item.isChecked)
);

const hasSelectedProducts = computed(() => selectedProducts.value.length > 0);

// 删除单个收藏
const deleteSingleProduct = async (favoriteId) => {
  if (!currentUser.value) return showLoginDialog.value = true;
  try {
    await axios.delete(`${API_URL}/favorites/${favoriteId}`);
    favoriteProducts.value = favoriteProducts.value.filter(
      (item) => item.id !== favoriteId
    );
    ElMessage.success("已移除收藏");
  } catch (error) {
    ElMessage.error("删除失败，请重试");
  }
};

// 批量删除选中收藏
const deleteSelectedProducts = async () => {
  if (!currentUser.value) return showLoginDialog.value = true;
  if (!hasSelectedProducts.value) return ElMessage.warning("请选择要删除的商品");

  try {
    const deletePromises = selectedProducts.value.map((item) =>
      axios.delete(`${API_URL}/favorites/${item.id}`)
    );
    await Promise.all(deletePromises);
    favoriteProducts.value = favoriteProducts.value.filter(
      (item) => !selectedProducts.value.includes(item)
    );
    ElMessage.success("已删除选中商品");
  } catch (error) {
    ElMessage.error("批量删除失败");
  }
};

// 全选功能
const selectAllProducts = () => {
  const allChecked = filteredProducts.value.every((item) => item.isChecked);
  favoriteProducts.value = favoriteProducts.value.map((item) => ({
    ...item,
    isChecked: !allChecked,
  }));
};

// 监听用户登录状态
watch(currentUser, (newUser) => {
  if (newUser) {
    loadFavorites();
  } else {
    favoriteProducts.value = [];
  }
}, { immediate: true });

onMounted(() => {
  if (currentUser.value) loadFavorites();
});
</script>

<style scoped>
#app {
  width: 100vw;
  height: auto;
  margin: 0;
  font-family: Avenir, Helvetica, Arial, sans-serif;
  padding: 0rem;
  text-align: center;
  color: #ffffff;
  display: flex;
  flex-direction: column;
}

.top-navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #E05649;
  padding: 10px 20px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.nav-link:hover {
  color: rgb(130, 69, 25);
  border-radius: 20%;
}

.nav-link {
  margin-right: 20px;
  text-decoration: none;
  color: rgb(255, 255, 255);
}

.sign-in-button,
.register-button,
.sign-out-button {
  background-color: #e05649;
  color: white;
  border: none;
  padding: 5px 10px;
  cursor: pointer;
}

.favorite-container {
  margin-top: 50px;
  display: flex;
  width: 100%;
  height: auto;
  background-color: #efefef;
  min-height: 400px;
}

.left-panel {
  width: 240px;
  padding: 20px;
  border-right: 1px solid #eee;
  background-color: #ffffff;
  position: fixed;
  top: 60px;
  bottom: 0;
  left: 0;
  overflow-y: auto;
  box-shadow: 2px 0 4px rgba(0, 0, 0, 0.1);
}

.filter-search {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.all-button {
  padding: 5px 10px;
  background-color: #e05649;
  color: white;
  border: none;
  cursor: pointer;
}

.category-button {
  padding: 5px 10px;
  background-color: #ffffff;
  color: #333;
  border: none;
  cursor: pointer;
}

.category-button:hover {
  background-color: #e05649;
  color: #fff;
}

.search-center {
  width: 100%;
  margin-top: 80px;
  height: 30px;
  align-self: center;
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  margin-right: 15%;
}

.search-input {
  padding: 5px;
  border-radius: 5px;
  border: 1px solid #ccc;
}

.search-icon {
  padding: 5px 10px;
  background-color: #fff;
  border: 1px solid #ccc;
  cursor: pointer;
}

.right-panel {
  flex: 1;
  padding: 20px;
  margin-left: 260px;
  display: flex;
  flex-direction: column;
}

.product-list {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.product-item {
  width: calc(90% - 20px);
  margin-bottom: 20px;
  border: 1px solid #ccc;
  padding: 10px;
  box-sizing: border-box;
  display: flex;
  border-radius: 10px;
  align-items: center;
  background-color: #ffffff;
}

.product-image {
  width: 100px;
  height: 100px;
  border-radius: 10px;
}

.product-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex: 1;
  margin-left: 10px;
  color: #333;
}

.delete-button {
  background-color: #e05649;
  color: white;
  border: none;
  padding: 5px 10px;
  cursor: pointer;
}

.delete-selected-button {
  width: calc(30% - 20px);
  padding: 10px;
  background-color: #333;
  color: white;
  border: none;
  cursor: pointer;
  margin-top: 20px;
  opacity: 0.5;
  pointer-events: none;
  margin-left: 35%;
}

.delete-selected-button:enabled {
  opacity: 1;
  pointer-events: auto;
}

.footer-links {
  border-top: 1px solid #eee;
  padding: 30px;
  text-align: center;
  margin-left: 260px;
}

.link-group {
  margin-bottom: 12px;
}

.link-group a {
  color: #999;
  font-size: 12px;
  margin: 0 12px;
  cursor: pointer;
}

.link-group a:hover {
  color: #230303;
}

.copyright {
  color: #ccc;
  font-size: 12px;
  margin-top: 20px;
}
</style>